package com.metel.mservice.common.context;

import java.net.URL;

import javax.servlet.ServletContext;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Log4jConfigurer;
import org.springframework.web.util.Log4jWebConfigurer;

/**
 * Context for ChatOn Developer.
 * 
 * @author 
 * 
 */
public class DefaultContext implements OpenAPIContext {

	private String env;

	public DefaultContext(String env) {
		this.env = env;
	}

	@Override
	public Resource getServerPropertyLocation(Resource location) {
		String fileName = location.getFilename();
		
		// parse fileName
		if ( fileName != null ) {
			if (fileName.lastIndexOf("/") > 0) {
				fileName = fileName.substring(fileName.lastIndexOf("/"));
			} else {
				fileName = "/" + fileName;
			}
	
			// add env to fileName
			String resourceName = null;
			if (fileName.indexOf("_" + env) > 0) {
				resourceName = fileName;
			} else {
				resourceName = getResourceNameFrom(fileName);
			}
	
			ClassPathResource realResource = new ClassPathResource(resourceName);
	
			return realResource;
		}
		
		return null;
	}

	@Override
	public void initializeWebLogger(ServletContext servletContext) {
		String fromContextFile = servletContext.getInitParameter(Log4jWebConfigurer.CONFIG_LOCATION_PARAM);

		String realLocation = getRealLocation(fromContextFile);
		if (realLocation != null) {
			try {
				// Write log message to server log.
				servletContext.log("Initializing log4j from [" + realLocation + "]");

				Log4jConfigurer.initLogging(realLocation);
			} catch (Exception ex) {
				throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());
			}
		}
	}

	@Override
	public boolean isProductionContext() {
		return false;
	}
	
	private String getRealLocation(String location) {
		String realLocation = null;

		if (location != null) {
			// parse fileName
			String fileName = null;
			if (location.lastIndexOf("/") > 0) {
				fileName = location.substring(location.lastIndexOf("/"));
			} else {
				fileName = "/" + location;
			}

			// add env to fileName
			String resourceName = getResourceNameFrom(fileName);

			// get source path
			URL resource = getClass().getResource(resourceName);
			if (resource != null) {
				String path = resource.getPath();
				if (path.startsWith("/")) {
					path = path.substring(1);
				}

				realLocation = "file:" + path;
			}
		}

		return realLocation;
	}

	private String getResourceNameFrom(String contextName) {
		String resourceName = null;
		int separator = contextName.lastIndexOf(".");
		if (separator > 0) {
			resourceName = contextName.substring(0, separator) + "_" + env + contextName.substring(separator);
		} else {
			resourceName = contextName + "_" + env;
		}

		return resourceName;
	}
}
